package com.kvest.testtask.network.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

public class HTTPPostRequest extends HTTPRequest
{
	private List<NameValuePair> params;
	
	public HTTPPostRequest(String url)
	{
		super(url);
		
		params = new ArrayList<NameValuePair>();
	}
	
	public void addParameter(String name, String value)
	{
		params.add(new BasicNameValuePair(name, value));
	}
	
	@Override
	public void run()
	{
		try
		{
			HttpPost request = new HttpPost(url);
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
			request.setEntity(formEntity);
			
			HttpResponse responce = client.execute(request);
			
			StringBuffer sb = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(responce.getEntity().getContent()));
			try
			{
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = reader.readLine()) != null)
				{
					sb.append(line + NL);
				}
			}
			finally
			{
				if (reader != null)
				{
					try
					{
						reader.close();
					}catch(IOException ioex){};
				}
			}
			
			result(HTTPRequestResult.RESULT_OK, sb.toString());
		}
		catch(Exception ex)
		{
			result(HTTPRequestResult.RESULT_ERROR, "");
		}
	}
}
